package com.example.demo.testpush.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hxk.sdk.server.ReceiveData;
import com.hxk.sdk.server.ResponseUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 测试推送接收数据（模拟渠道接收数据）
 *
 * @author hxk
 */
@Slf4j
@RestController
@RequestMapping("/testPush")
public class TestPushController {
    /**
     * 渠道的私钥(需替换正确key)
     */
    private final static String CHANNEL_PRIVATE_KEY = "CHANNEL_PRIVATE_KEY";
    /**
     * 和信康公司分配的公钥(需替换正确key)
     */
    private final static String HXK_PUBLIC_KEY = "HXK_PUBLIC_KEY";

    /**
     * 接收用户数据接口
     *
     * @param s 接收json字符串
     * @return JSONObject
     */
    @RequestMapping("/user")
    public JSONObject userInterface(@RequestBody String s) {
        log.info(s);
        JSONObject jsonObject = JSON.parseObject(s);
        String encryptkey = jsonObject.getString("encryptkey");
        String encryptdata = jsonObject.getString("encryptdata");

        // 验证请求
        ReceiveData receiveData = ResponseUtil.receive(encryptkey, encryptdata, HXK_PUBLIC_KEY, CHANNEL_PRIVATE_KEY);
        // 通过和信康SDK验证请求异常
        if (receiveData.getCode() != 0) {
            log.error("请求验证异常");
            return null;
        }
        log.info(receiveData.getData().toString());

        JSONObject j = new JSONObject();
        j.put("code", 200);
        return j;
    }

    /**
     * 接收检测数据接口
     *
     * @param s 接收json字符串
     * @return JSONObject
     */
    @RequestMapping("/check")
    public JSONObject checkInterface(@RequestBody String s) {
        log.info(s);
        JSONObject jsonObject = JSON.parseObject(s);
        String encryptkey = jsonObject.getString("encryptkey");
        String encryptdata = jsonObject.getString("encryptdata");

        // 验证请求
        ReceiveData receiveData = ResponseUtil.receive(encryptkey, encryptdata, HXK_PUBLIC_KEY, CHANNEL_PRIVATE_KEY);
        // 通过和信康SDK验证请求异常
        if (receiveData.getCode() != 0) {
            log.error("请求验证异常");
            return null;
        }
        log.info(receiveData.getData().toString());

        JSONObject j = new JSONObject();
        j.put("code", 200);
        return j;
    }
}
